# -*- coding: utf-8 -*-
from common.settlement.model import BankCard, Settlement, SettlementOrder
from common.utils.decorator import sql_wrapper
from common.utils.db import list_object, get, upsert, delete
from common.utils.exceptions import ParamError


@sql_wrapper
def get_bankcard(id):
    return get(BankCard, id)


@sql_wrapper
def upsert_bankcard(info, id=None):
    bank_card = BankCard.query.filter(BankCard.account_number == info['account_number']).first()
    id = bank_card.id if bank_card else None
    return upsert(BankCard, info, id)


@sql_wrapper
def list_bankcard(query_dct):
    return list_object(query_dct, BankCard)


@sql_wrapper
def delete_bankcard(id):
    delete(BankCard, id)


@sql_wrapper
def get_settlement(id):
    return get(Settlement, id)


@sql_wrapper
def upsert_settlement(info, id=None):
    return upsert(Settlement, info, id)


@sql_wrapper
def create_settlement_withdraw(info):
    upsert_settlement_order(info)
    if info.get('channel_id'):
        s = Settlement.query.filter(Settlement.chn_id == int(info['channel_id'])).first()
        if s.balance is not None:
            if float(info['total_fee']) > float(s.balance):
                raise ParamError('settlement amount can not bigger than balance')
            s.balance = float(s.balance) - float(info['total_fee'])
        else:
            s.balance = 0
        s.today_withdraw = float(s.today_withdraw) + float(info['total_fee'])
        s.save()


@sql_wrapper
def list_settlement(query_dct):
    return list_object(query_dct, Settlement)


@sql_wrapper
def delete_settlement(id):
    delete(Settlement, id)


@sql_wrapper
def get_settlement_order(id):
    return get(SettlementOrder, id)


@sql_wrapper
def upsert_settlement_order(info, id=None):
    return upsert(SettlementOrder, info, id)


@sql_wrapper
def list_settlement_order(query_dct):
    return list_object(query_dct, SettlementOrder)


@sql_wrapper
def delete_settlement_order(id):
    delete(SettlementOrder, id)


@sql_wrapper
def get_bankcard_by_card_num(card_num):
    return BankCard.query.filter(BankCard.card_num == card_num).first()


@sql_wrapper
def get_bankcard_list():
    return BankCard.query.all()
